package com.example.aboutspringboot.controller;

import com.example.aboutspringboot.entity.User;
import com.example.aboutspringboot.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController //为了接收json格式的数据
@RequestMapping("user")
@CrossOrigin//跨域
public class UserController {

    @Resource
    UserMapper userMapper;

    @GetMapping("/findAll")
    public Map<String,Object> findAll(){
        Map<String, Object> map = new LinkedHashMap<>();
        List<User> results = userMapper.findAll();
        map.put("results", results);
        return map;
    }

    @PostMapping("/add")
    //@RequestBody注解才可以正确的解析JSON数据，否则什么都拿不到
    public Map<String,Object> add(@RequestBody User user){
        Map<String,Object> map=new LinkedHashMap<>();
        int count=userMapper.add(user);
        if (count==1){//正确插入数据库
            map.put("success",true);
            map.put("msg","添加成功");
        }else if(count<1){
            map.put("success",false);
            map.put("msg","添加失败");
        }
        return map;
    }

    @PostMapping("/edit")
    public Map<String,Object> edit(@RequestBody User user){
        Map<String,Object> map=new LinkedHashMap<>();
        int count=userMapper.update(user);
        if (count==1){//正确修改数据库
            map.put("success",true);
            map.put("msg","修改成功");
        }else if(count<1){
            map.put("success",false);
            map.put("msg","修改失败");
        }
        return map;
    }
    @PostMapping("/delete")
    public Map<String,Object> delById(@RequestBody User user){
        Map<String,Object> map=new LinkedHashMap<>();
        try {//正确修改数据库
            userMapper.delById(user.getId());
            map.put("success",true);
            map.put("msg","删除成功");
        }catch (Exception e){
            map.put("success",false);
            map.put("msg","删除失败，请稍后再试..");
        }
        return map;
    }
}
